package com.wh1200.mybatis.xmlless.util

import com.wh1200.kotlin.isNotNullAndNotBlank
import com.wh1200.mybatis.xmlless.constant.Strings
import com.wh1200.mybatis.xmlless.constant.Strings.LINE_BREAK

/**
 *
 * @author 吴昊
 * @date 2023/12/12 23:40
 * @since v4.0.0
 * @version 1.0
 */
object ScriptUtils {

  private const val RIGHT_BRACE: String = "}"
  private const val HASH_LEFT_BRACE: String = "#{"

  fun convertTrim(script: String, suffix: String): String {
    return """<trim suffixOverrides="$suffix">
  %s
    </trim>""".format(script)
  }

  fun convertIf(sqlScript: String, ifTest: String, newLine: Boolean, tag: String = "if"): String {
    if (ifTest.isBlank()) {
      return sqlScript
    }
    var newSqlScript = sqlScript
    if (newLine) {
      newSqlScript = "$LINE_BREAK  $newSqlScript$LINE_BREAK"
    }
    return String.format("""<${tag} test="%s">%s</${tag}>""", ifTest, newSqlScript)
  }

  fun convertTrim(
      sqlScript: String?, prefix: String?, suffix: String?,
      prefixOverrides: String?, suffixOverrides: String?
  ): String {
    val sb = StringBuilder("<trim")
    if (prefix.isNotNullAndNotBlank()) {
      sb.append(" prefix=\"").append(prefix).append(Strings.QUOTE)
    }
    if (suffix.isNotNullAndNotBlank()) {
      sb.append(" suffix=\"").append(suffix).append(Strings.QUOTE)
    }
    if (prefixOverrides.isNotNullAndNotBlank()) {
      sb.append(" prefixOverrides=\"").append(prefixOverrides).append(Strings.QUOTE)
    }
    if (suffixOverrides.isNotNullAndNotBlank()) {
      sb.append(" suffixOverrides=\"").append(suffixOverrides).append(Strings.QUOTE)
    }
    return sb.append(">").append(LINE_BREAK).append(sqlScript).append(LINE_BREAK)
        .append("</trim>").toString()
  }

  fun safeParam(param: String): String {
    return HASH_LEFT_BRACE + param + RIGHT_BRACE
  }

}
